#region Using References

using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Beaker.OpenCube.CubeManager.Model.Configurations;
using Beaker.OpenCube.CubeManager.Model.Entities;

#endregion

namespace Beaker.OpenCube.CubeManager.Model.Migrations
{
	internal sealed class Configuration
		: DbMigrationsConfiguration<CubeManagerDbContext>
	{
		public Configuration()
		{
			AutomaticMigrationsEnabled = false;
		}

		protected override void Seed( CubeManagerDbContext context )
		{
			var roles = context.Set<Role>();
			var roleSets = context.Set<RoleSet>();
			var users = context.Set<User>();

			var adminRole = roles.SingleOrDefault( r => r.Name == "Administrator" );
			if( adminRole == null )
			{
				adminRole = new Role( "Administrator" );
				roles.Add( adminRole );
			}

			var adminUser = users.SingleOrDefault( u => u.Name == "Administrator" );
			if( adminUser == null )
			{
				adminUser = new User( "Administrator" );
				users.Add( adminUser );
			}

			var adminRoleSets =
				roleSets
					.Where( rs => rs.User.Id == adminUser.Id )
					.Where( rs => rs.Roles.Any( r => r.Id == adminRole.Id ) );
			if( !adminRoleSets.Any() )
			{
				var adminRoleSet = new RoleSet( adminUser );
				adminRoleSet.Roles.Add( adminRole );
			}
		}
	}
}
